"""
BeaverFramework Remote Server Module

This module implements a RESTful API server for the BeaverFramework, providing remote access
to framework functionalities and task management capabilities.

Authors:
    MichaelZhang

Key Features:
    - RESTful API endpoints for task submission and monitoring
    - JSON-based communication protocol
    - Task status tracking
    - Error handling and response formatting

Usage:
    # Run the server
    python server.py
    
    # Access API endpoints
    POST http://server_ip:5010/API102
    GET http://server_ip:5010/API102
"""

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

# Dictionary to store API endpoints and their associated functions
APIs = {}
project_base = '/home/ly/GitRepo/lubandigitalframe'

class APISimple(Resource):
    """
    REST API resource handler for the BeaverFramework.
    
    This class provides endpoints for submitting new tasks and checking task status.
    It handles both GET and PUT requests, supporting task monitoring and submission
    respectively.

    Endpoints:
        GET /<API_id>: Retrieve status or information for a specific API
        PUT /<API_id>: Submit new task or update existing API data

    Attributes:
        APIs (dict): Global dictionary storing API endpoint configurations
    """

    def get(self, API_id):
        """
        Handle GET requests for API status retrieval.

        Args:
            API_id (str): Identifier for the specific API endpoint

        Returns:
            dict: Response containing the API status or information
                Format: {API_id: value}

        Example:
            GET /API102 -> {"API102": "status_value"}
        """
        return {API_id: APIs[API_id]}

    def put(self, API_id):
        """
        Handle PUT requests for task submission and API updates.

        This method processes incoming PUT requests, handling both new task submissions
        and status updates. It supports different types of operations based on the
        API name provided.

        Args:
            API_id (str): Identifier for the specific API endpoint

        Returns:
            dict: Response containing operation result or error message
                Success formats:
                    - New task: {API_id: {"task_details": "..."}}
                    - Status update: {API_id: {"work_id": "status"}}
                Error formats:
                    - {"error": "request.json not work"}
                    - {"error": "API name is not exsit, please check spelling"}

        Example:
            PUT /API102 {"name": "newtask_job_submit", ...} -> {"API102": {"task_details": ...}}
        """
        try:
            data_body = request.json
            APIs[API_id] = data_body["name"]
            print(f"Received request for API: {APIs[API_id]}")
        except:
            return {"error": "request.json not work"}

        if APIs[API_id] == "":
            return {"error": "API name is not exsit, please check spelling"}

        if APIs[API_id] == "newtask_job_submit":
            # Handle new task submission
            print('submiting new task now')
            res = request.json
            print('res------------', res)
            res_value = res
            return {API_id: res_value}
        
        elif APIs[API_id] == "check_work_status_by_work_id":
            print('checking task status now')
            res = request.json
            status = "Work is DONE!"
            return {API_id:
                {res["work_id"] : status}}
#add to resource of APIs    
api.add_resource(APISimple, '/<string:API_id>')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5010, debug=True)
